package com.xforceplus.bsstool.db;

import com.xforceplus.bsstool.config.ConfigMain;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 老运营UCENTER数据库连接
 */
public class OldUcenterDB {
  private static final Logger logger = LoggerFactory.getLogger(OldUcenterDB.class);
  private static Connection conn = null;
  private static Map<String,List<Map>> dataCacheMap = new HashMap<>();

  public static void releaseConnection(){
    if (conn!=null) {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      conn=null;
    }
  }

  public static List<Map> getSqlResultByCache(String tableName ,Map<String,Object> eqKeyValueMap
          ,Map<String,Object> nqKeyValueMap)  throws Exception {
    List<Map> dataList = dataCacheMap.get(tableName);
    if (CollectionUtils.isEmpty(dataList)){
      //缓存没有记录，则从数据库获取
      dataList = getSqlResult("select * from "+tableName,null);
      dataCacheMap.put(tableName,dataList);
    }
    //从缓存获取
    List<Map> retList = new ArrayList<>();
    boolean continueFlag = false;
    Iterator<Map.Entry<String, Object>> nqIterator;
    Map.Entry<String, Object> nqEntry;

    Iterator<Map.Entry<String, Object>> eqIterator;
    Map.Entry<String, Object> eqEntry;
    for (Map data : dataList){
      if (nqKeyValueMap != null) {
        nqIterator = nqKeyValueMap.entrySet().iterator();
        while (nqIterator.hasNext()) {
          nqEntry = nqIterator.next();
          if (nqEntry.getValue().equals(data.get(nqEntry.getKey()))){
            continueFlag = true;
            break;
          }
        }
      }
      if (continueFlag) continue;

      if (eqKeyValueMap != null) {
        eqIterator = eqKeyValueMap.entrySet().iterator();
        while (eqIterator.hasNext()) {
          eqEntry = eqIterator.next();
          if (!eqEntry.getValue().equals(data.get(eqEntry.getKey()))){
            continueFlag = true;
            break;
          }
        }
      }
      if (continueFlag) continue;

      retList.add(data);
    }
    return retList;
  }

  public static List<Map> getSqlResult(String sql,Object... objects) throws Exception {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    try {
      if (conn == null) {
        Class.forName("com.mysql.jdbc.Driver");
        // 设置SSH本地端口转发后，访问本地ip+port就可以访问到远程的ip+port
        conn = DriverManager.getConnection(ConfigMain.OLD_UCENTER_DB_URL, ConfigMain.OLD_UCENTER_DB_USER_NAME, ConfigMain.OLD_UCENTER_DB_PASSWORD);
      }
      preparedStatement = conn.prepareStatement(sql);
      //设置参数
      if (objects != null && objects.length > 0) {
        for (int i = 0; i < objects.length; i++) {
          preparedStatement.setObject(i + 1, objects[i]);
        }
      }

      rs = preparedStatement.executeQuery();
      List<Map> resultList = new ArrayList<>();
      while (rs.next()) {
        Map resultMap = new HashMap();
        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        for (int i=1; i<=columnCount; i++) {
          resultMap.put(resultSetMetaData.getColumnLabel(i), rs.getObject(i));
        }
        resultList.add(resultMap);
      }
      return resultList;
    } catch (Exception e) {
      logger.error("获取老运营UCENTER数据信息异常",e);
      throw e;
    } finally {
      if (rs!=null) {rs.close();rs=null;}
      if (preparedStatement!=null) {
        preparedStatement.close();
        preparedStatement=null;
      }
      if (conn!=null) {
        conn.close();
        conn=null;
      }
    }
  }



  public static void main(String[] args) throws Exception {
    List<Map> resultList = getSqlResult("select * from sys_role where role_id = 1 ");
    System.out.println("resultList:"+resultList);
  }

}
